<?php

class MY_Benchmark extends CI_Benchmark {

	function __destruct(){
		$this->_save_stats_to_file();
	}

	private function _save_stats_to_file(){
		$date = date('Y-m-d');
		
		chdir(FCPATH);
		
		$file = APPPATH . "private/temp/profiling/Profiling-{$date}.csv";

		$fp = @fopen($file, "ab");

		if(!$fp){
			$message = "Could not open/create file '{$file}' for writing. Please check permissions.";
			echo $message;
			log_message("error",$message);
			
			return;
		}
		
		$csv_titles = array("Mark", "Load time (sec)", "Timestamp", "Date time");
		
		$session_id = "DISPLAYING FROM CACHE";
		if(class_exists("CI_Controller"))
			$session_id = get_instance()->session->userdata('session_id');
		
		fputcsv($fp, array("Session: {$session_id}"), ",", "\"");
		fputcsv($fp, array(""), ",", "\"");
		fputcsv($fp, $csv_titles, ",", "\"");
		
		foreach ($this->marker as $mark=>$data){
		
			$data = explode(" ", $data);
			$line = array(
				$mark,
				$data[0],
				$data[1],
				date("Y-m-d H:i:s.u", $data[1])
			);

			fputcsv($fp, $line, ",", "\"");
		}
		
		fputcsv($fp, array(""), ",", "\"");
		fclose($fp);
	}
}